<template>
    <view class="savepadding">
        <view class="step-wrap">
            <view class="line"></view>
            <view class="step-item active">上传客户证件</view>
            <view class="step-item active">扣款订单信息</view>
        </view>
        <view class="wrap">
            <view class="header">
                <view class="title">客户信息</view>
            </view>
            <view class="list">
                <view class="label">客户类型</view>
                <view class="value">{{activeCustomtype.dictLabel}}</view>
            </view>
            <template v-if="activeCustomtype.dictLabel=='企业'">
                <view class="list">
                    <view class="label">企业名称</view>
                    <view class="value">{{customForm.customerName}}</view>
                </view>
            </template>
            <view class="list">
                <view class="label">{{activeCustomtype.dictLabel=='企业'?'联系人':'客户姓名'}}</view>
                <view class="value">
                    {{activeCustomtype.dictLabel=='企业'?customForm.contactPerson:customForm.customerName}}
                </view>
            </view>
            <view class="list">
                <view class="label">身份证号码</view>
                <view class="value">{{customForm.idCardNo}}</view>
            </view>
            <template v-if="customForm.customerFlag != 3">
                <view class="list">
                    <view class="label">银行预留手机号</view>
                    <view class="value">{{bankForm.mobileNo}}</view>
                </view>
                <view class="list">
                    <view class="label">开户行</view>
                    <view class="value">{{bankForm.bankDeposit}}</view>
                </view>
                <view class="list">
                    <view class="label">银行卡号</view>
                    <view class="value">{{bankForm.bankCardNo}}</view>
                </view>
            </template>
        </view>
        <view class="wrap">
            <view class="header">
                <view class="title">扣款信息*</view>
            </view>
            <view class="list">
                <view class="label">扣款业务类型</view>
                <view class="value"
                      style="display:flex"
                      @click="showBusinessData=true">
                    <!-- <text>{{orderForm.businessType||'请选择扣款业务类型'}}</text> -->
                    <text>{{selectedBusinessData.businessName||'请选择扣款业务类型'}}</text>
                    <u-icon name="arrow-right"></u-icon>
                </view>
            </view>
            <view class="list">
                <view class="label">扣款总金额</view>
                <view class="value">
                    <u--input border="none"
                              inputAlign="right"
                              type="number"
                              fontSize="24upx"
                              v-model="orderForm.totalFee"
                              placeholder="请输入扣款总金额"
                              @input="resetFeeFormFee" />
                </view>
            </view>
            <view class="list">
                <view class="label">分期类型</view>
                <view class="value"
                      style="display:flex"
                      @click="showInstallMentType=true">
                    <!-- <text>{{orderForm.decutionType||'请选择分期类型'}}</text> -->
                    <text>{{selectedInstallMentType.dictLabel||'请选择分期类型'}}</text>
                    <u-icon name="arrow-right"></u-icon>
                </view>
            </view>
            <template v-if="customForm.customerFlag != 3">
                <u-divider dashed></u-divider>
                <view class="list">
                    <view class="label">客户短信授权通知</view>
                    <view class="value">
                        <u--text type="primary"
                                 align="right"
                                 text="协议说明"
                                 @click="showxieyi=true"></u--text>
                    </view>
                </view>
                <view class="list">
                    <view class="label">银行预留手机号</view>
                    <view class="value">
                        <u--input border="none"
                                  inputAlign="right"
                                  type="number"
                                  fontSize="24upx"
                                  v-model="bankForm.mobileNo"
                                  placeholder="请输入手机号" />
                    </view>
                </view>
                <view class="list">
                    <view class="label">手机验证码</view>
                    <view class="value"
                          style="display:flex; align-items:center">
                        <u--input border="none"
                                  inputAlign="right"
                                  type="number"
                                  fontSize="24upx"
                                  v-model="bankForm.authCode"
                                  placeholder="请输入验证码" />
                        <view v-if="captchaCD>0"
                              style="margin-left:10upx">{{captchaCD}}秒后重发</view>
                        <view @click="getCaptcha"
                              style="margin-left:10upx"
                              v-else>获取验证码</view>
                    </view>
                </view>
            </template>
        </view>
        <template v-if="selectedInstallMentType.dictLabel=='分期'">
            <view class="wrap">
                <view class="header">
                    <view class="title">分期信息*</view>
                </view>
                <view class="list">
                    <view class="label">扣款期数</view>
                    <view class="value">
                        <u-number-box v-model="orderForm.decutionNum"
                                      @change="onChangeDecutiomNum">
                            <text slot="input"
                                  style="width: 50px;text-align: center">{{orderForm.decutionNum}}/期</text>
                        </u-number-box>
                    </view>
                </view>
                <view class="list">
                    <view class="label">扣款模式（金额）</view>
                    <view class="value"
                          style="display:flex"
                          @click="showDecutionMode=true">
                        <!-- <text>{{orderForm.decutionPattern||'请选择扣款模式'}}</text> -->
                        <text>{{selectedDecutionMode.dictLabel||'请选择扣款模式'}}</text>
                        <u-icon name="arrow-right"></u-icon>
                    </view>
                </view>
                <view class="list">
                    <view class="label">扣款间隔（时间）</view>
                    <view class="value"
                          style="display:flex"
                          @click="showDecutionInterval=true">
                        <!-- <text>{{orderForm.decutionInterval||'请选择扣款间隔'}}</text> -->
                        <text>{{selectedDecutionInterval.dictLabel||'请选择扣款间隔'}}</text>
                        <u-icon name="arrow-right"></u-icon>
                    </view>
                </view>
                <view class="list">
                    <view class="label">首期扣款日期</view>
                    <view class="value"
                          style="display:flex"
                          @click="openDatetimePicker(orderForm, 'firstDecutionTime')">
                        <text>{{orderForm.firstDecutionTime||$u.timeFormat(new Date().getTime())}}</text>
                        <u-icon name="arrow-right"></u-icon>
                    </view>
                </view>
            </view>
            <view class="wrap"
                  v-if="feeFormList.length">
                <view class="header">
                    <view class="title">分期明细*</view>
                </view>
                <view class="table">
                    <view class="table-h">
                        <view>分期数</view>
                        <view>扣款日期</view>
                        <view>扣款金额</view>
                    </view>
                    <template v-for="item in feeFormList">
                        <view class="table-b"
                              :key="item.stage">
                            <view>第{{item.stage}}期</view>
                            <view @click="setFeeFormTime(item)">{{item.expectDecutionTime}}</view>
                            <view>
                                <u-input type="number"
                                         border="none"
                                         fontSize="26rpx"
                                         inputAlign="right"
                                         placeholder="请输入"
                                         :readonly="selectedDecutionMode.dictLabel!='每期自由输入'"
                                         @input="setFeeInput($event, item)"
                                         v-model="item.expectDecutionFee">
                                    <template v-slot:suffix>
                                        <!-- :readonly="selectedDecutionMode.dictLabel!='每期自由输入'||item.stage>=feeFormList.length" -->
                                        ￥
                                    </template>
                                </u-input>
                            </view>
                        </view>
                    </template>
                </view>
            </view>
        </template>
        <view class="btn-btm-group-wrap">
            <view class="btn-btm-group savepadding">
                <view class="btn-btm"
                      @click="pre">上一步</view>
                <view class="btn-btm active"
                      @click="next">提交订单</view>
            </view>
        </view>
        <!-- 协议弹窗 -->
        <Maskxieyi v-if="showxieyi"
                   @ok="showxieyi=false"></Maskxieyi>
        <!-- 选择扣款业务类型 -->
        <u-picker :show="showBusinessData"
                  :columns="[businessData]"
                  keyName="businessName"
                  @confirm="confirmBusinessData"
                  @cancel="showBusinessData=false"></u-picker>
        <!-- 选择分期类型 -->
        <u-picker :show="showInstallMentType"
                  :columns="[installMentType]"
                  keyName="dictLabel"
                  @confirm="confirmInstallMentType"
                  @cancel="showInstallMentType=false"></u-picker>
        <!-- 选择扣款模式 -->
        <u-picker :show="showDecutionMode"
                  :columns="[decutionMode]"
                  keyName="dictLabel"
                  @confirm="confirmDecutionMode"
                  @cancel="showDecutionMode=false"></u-picker>
        <!-- 选择扣款间隔 -->
        <u-picker :show="showDecutionInterval"
                  :columns="[decutionInterval]"
                  keyName="dictLabel"
                  @confirm="confirmDecutionInterval"
                  @cancel="showDecutionInterval=false"></u-picker>
        <!-- 首期扣款日期 -->
        <u-datetime-picker :show="showDatetimePicker"
                           :formatter="formatter"
                           :minDate="selectedDatetimePicker.minDate"
                           :maxDate="selectedDatetimePicker.maxDate"
                           mode="date"
                           ref="datetimePicker"
                           v-model="defaultDatetimePick"
                           @confirm="confirmDatetimePicker"
                           @cancel="showDatetimePicker=false"></u-datetime-picker>
        <!-- 提交订单提示 -->
        <u-modal :show="showSubmitModal"
                 title="提交订单"
                 :showCancelButton="true"
                 :asyncClose="true"
                 @confirm="submitOrder"
                 @cancel="showSubmitModal=false">
            <view style="text-align:center">是否提交并支付订单</view>
        </u-modal>
    </view>
</template>

<script>
import * as systemApi from '@/api/system-api'
import * as orderApi from '@/api/order-api'
import qianyue from '@/pagesA/mixins/qianyue'
import Maskxieyi from '@/components/mmv-ui/mask-xieyi.vue'

export default {
    components: {
        Maskxieyi,
    },
    mixins: [qianyue],
    data() {
        return {
            showSubmitModal: false,
            businessData: [], // 扣款业务类型（数据列表）
            installMentType: [], // 分期类型（数据列表）
            decutionMode: [], // 扣款模式（数据列表）
            decutionInterval: [], // 扣款间隔（数据列表）
            showxieyi: false, // 显示协议（显示控制）
            showBusinessData: false, // 扣款业务类型（显示控制）
            showInstallMentType: false, // 分期类型（显示控制）
            showDecutionMode: false, // 扣款模式（显示控制）
            showDecutionInterval: false, // 扣款间隔（显示控制）
            showDatetimePicker: false, // 公共时间选择器（显示控制）
            selectedBusinessData: {}, // 扣款业务类型（当前选择）
            selectedInstallMentType: {}, // 分期类型（当前选择）
            selectedDecutionMode: {}, // 扣款模式（当前选择）
            selectedDecutionInterval: {}, // 扣款间隔（当前选择）
            selectedDatetimePicker: {  // 公共时间选择器（当前选择）
                minDate: new Date().getTime(),
                maxDate: new Date(new Date().getFullYear() + 10, 0, 1).getTime(),
                target: {}, // 时间设置项
                key: '', // 时间设置字段
            },
            defaultDatetimePick: new Date().getTime(), // 时间选择器默认时间
            captchaTimer: null, // 验证码计时器
            captchaCD: 0, // 验证码倒计时
        }
    },
    computed: {

    },
    watch: {

    },
    onReady() {
        // 微信小程序需要用此写法
        this.$refs.datetimePicker.setFormatter(this.formatter)
    },
    onLoad(op) {
        const data = JSON.parse(op.data || '{}');
        // 合并参数
        Object.assign(this.$data, data);
        Object.keys(data).forEach((val) => {
            this[val] = data[val];
        });
        console.log('data', data);
        console.log('$data', this.$data);
    },
    async mounted() {
        try {
            this.getBusinessData(); // 获取扣款业务类型
            this.getInstallMentType(); // 获取分期类型
            this.getDecutionMode(); // 获取扣款模式
            this.getDecutionInterval(); // 获取扣款间隔
        } catch (error) {
            console.error(error);
            const title = error?.message || '网络错误';
            uni.showToast({ title, icon: 'error' });
        }
    },
    methods: {
        pre() {
            uni.navigateBack();
        },
        async next() {
            try {
                await this.placeOrder();
                this.showSubmitModal = true;
            } catch (error) {
                uni.showToast({ title: error, icon: 'error' });
            }
        },
        formatter(type, value) {
            if (type === 'year') {
                return `${value}年`
            }
            if (type === 'month') {
                return `${value}月`
            }
            if (type === 'day') {
                return `${value}日`
            }
            return value
        },
        /**
         * 获取扣款业务类型
         */
        async getBusinessData() {
            try {
                const result = await orderApi.getBusinessData();
                this.businessData = result.data;
            } catch (error) {
                return Promise.reject(error);
            }
        },
        /**
         * 获取分期类型
         */
        async getInstallMentType() {
            try {
                const result = await systemApi.dict('installment_type');
                this.installMentType = result.data;
            } catch (error) {
                return Promise.reject(error);
            }
        },
        /**
         * 获取扣款模式
         */
        async getDecutionMode() {
            try {
                const result = await systemApi.dict('decution_mode');
                this.decutionMode = result.data;
                this.confirmDecutionMode({ value: result.data }); // 选择默认
            } catch (error) {
                return Promise.reject(error);
            }
        },
        /**
         * 获取扣款间隔
         */
        async getDecutionInterval() {
            try {
                const result = await systemApi.dict('decution_inteerval');
                this.decutionInterval = result.data;
                this.confirmDecutionInterval({ value: result.data }); // 选择默认
            } catch (error) {
                return Promise.reject(error);
            }
        },
        /**
         * 选择扣款业务类型(确认选择)
         */
        confirmBusinessData({ value }) {
            this.selectedBusinessData = value[0] || {};
            this.orderForm.businessType = this.selectedBusinessData.id;
            // this.orderForm.businessType = this.selectedBusinessData.businessName;
            this.showBusinessData = false;
        },
        /**
         * 选择分期类型(确认选择)
         */
        confirmInstallMentType({ value }) {
            this.selectedInstallMentType = value[0] || {};
            this.orderForm.decutionType = this.selectedInstallMentType.dictValue;
            // this.orderForm.decutionType = this.selectedInstallMentType.dictLabel;
            this.showInstallMentType = false;
            if (this.selectedInstallMentType.dictLabel == '分期') {
                this.onChangeDecutiomNum({ value: 1 });
            }
        },
        /**
         * 选择扣款模式(确认选择)
         */
        confirmDecutionMode({ value }) {
            this.selectedDecutionMode = value[0] || {};
            this.orderForm.decutionPattern = this.selectedDecutionMode.dictValue;
            // this.orderForm.decutionPattern = this.selectedDecutionMode.dictLabel;
            this.showDecutionMode = false;
            if (uni.$u.test.contains(this.selectedDecutionMode.dictLabel, '平均')) {
                this.resetFeeFormFee();
            }
        },
        /**
         * 选择扣款间隔(确认选择)
         */
        confirmDecutionInterval({ value }) {
            this.selectedDecutionInterval = value[0] || {};
            this.orderForm.decutionInterval = this.selectedDecutionInterval.dictValue;
            // this.orderForm.decutionInterval = this.selectedDecutionInterval.dictLabel;
            this.showDecutionInterval = false;
            this.resetFeeFormTime(new Date(this.orderForm.firstDecutionTime.replace(/-/g, "/")).getTime()); // 重设每期预计扣款时间
        },
        /**
         * 扣款期数变更
         */
        onChangeDecutiomNum({ value }) {
            this.feeFormList = [];
            for (let i = 1; i <= value; i++) {
                this.feeFormList.push({
                    stage: i, // 期数
                    expectDecutionTime: '', // 预计扣款时间
                    expectDecutionFee: 0, // 预计扣款金额
                });
            }
            this.resetFeeFormTime(new Date(this.orderForm.firstDecutionTime.replace(/-/g, "/")).getTime()); // 重设每期预计扣款时间
            this.resetFeeFormFee(); // 重设每期预计扣款金额
        },
        /**
         * 重设每期预计扣款时间
         */
        resetFeeFormTime(start = new Date().getTime()) {
            this.feeFormList.forEach((value, index, array) => {
                if (index == 0) {
                    value.expectDecutionTime = uni.$u.timeFormat(start);
                } else {
                    const suffix = array[index - 1];
                    const mmv = uni.$u.timeFormat(new Date(suffix.expectDecutionTime.replace(/-/g, "/")).getTime()).split('-');
                    if (mmv[1] < 12) {
                        mmv[1] = Number(mmv[1]) + 1;
                        // if (mmv[1] == 2 && mmv[2] > 28) {
                        //     mmv[2] = 28;
                        // }
                    } else { // 满年进一
                        mmv[0] = Number(mmv[0]) + 1;
                        mmv[1] = 1;
                    }
                    value.expectDecutionTime = uni.$u.timeFormat(new Date(mmv.join('/')).getTime());
                    // console.log('suffix', suffix);
                    // console.log('mmv', mmv);
                    // console.log("mmv.join('/')", mmv.join('/'), new Date(mmv.join('/')), new Date(mmv.join('/')).getTime());
                    // console.log('value.expectDecutionTime', value.expectDecutionTime);
                }
            });
        },
        /**
         * 重设每期预计扣款金额
         */
        resetFeeFormFee() {
            const sumBy = require('lodash/sumBy');
            this.feeFormList.forEach((value, index, array) => {
                if (index > 0) {
                    const mmv = Math.floor(this.orderForm.totalFee / array.length);
                    value.expectDecutionFee = mmv > 0 ? mmv : 0;
                } else {
                    value.expectDecutionFee = 0;
                }
            });
            const total = sumBy(this.feeFormList, val => Number(val.expectDecutionFee));
            const lastItem = this.feeFormList[0] || {};
            if (this.orderForm.totalFee - total > 0) {
                lastItem.expectDecutionFee = this.orderForm.totalFee - total;
            } else {
                lastItem.expectDecutionFee = 0;
            }
        },
        /**
         * 自由输入保护
         */
        setFeeInput(value, item) {
            // if (!Number(value)) {
            //     item.expectDecutionFee = 0;
            // }
        },
        /**
         * 选择时间(打开选择)
         */
        openDatetimePicker(target, key) {
            const stage = Number(target.stage);
            if (stage) {
                const prefix = this.feeFormList.find(val => val.stage == stage - 1);
                const suffix = this.feeFormList.find(val => val.stage == stage + 1);
                if (prefix) {
                    this.selectedDatetimePicker.minDate = Number(new Date(prefix.expectDecutionTime.replace(/-/g, "/"))) + (1000 * 60 * 60 * 24)
                } else {
                    this.selectedDatetimePicker.minDate = new Date().getTime();
                }
                if (suffix) {
                    this.selectedDatetimePicker.maxDate = Number(new Date(suffix.expectDecutionTime.replace(/-/g, "/"))) - (1000 * 60 * 60 * 24)
                } else {
                    this.selectedDatetimePicker.maxDate = new Date(new Date().getFullYear() + 10, 0, 1).getTime();
                }
            } else {
                this.selectedDatetimePicker.minDate = new Date().getTime();
                this.selectedDatetimePicker.maxDate = new Date(new Date().getFullYear() + 10, 0, 1).getTime();
            }
            this.selectedDatetimePicker.target = target;
            this.selectedDatetimePicker.key = key;
            this.showDatetimePicker = true;
        },
        /**
         * 选择时间(确认选择)
         */
        confirmDatetimePicker({ value }) {
            const _value = this.$u.timeFormat(value);
            this.selectedDatetimePicker.target[this.selectedDatetimePicker.key] = _value;
            const stage = Number(this.selectedDatetimePicker.target.stage);
            if (!stage) {
                this.resetFeeFormTime(value);
            }
            this.selectedDatetimePicker.target = {};
            this.selectedDatetimePicker.key = '';
            this.showDatetimePicker = false;
        },
        /**
         * 设置自定义间隔
         */
        setFeeFormTime(target) {
            if (
                target.stage > 1 &&
                this.selectedDecutionInterval.dictLabel == '自定义间隔'
            ) {
                this.openDatetimePicker(target, 'expectDecutionTime');
            }
        },
        /**
         * 获取验证码
         */
        async getCaptcha() {
            if (!uni.$u.test.mobile(this.bankForm.mobileNo)) {
                uni.showToast({ title: '手机号格式错误', icon: 'error' });
                return;
            }
            this.resetOrderNo(); // 重设签约订单编号
            uni.showToast({ title: '获取验证码中...', icon: 'loading' });
            try {
                const result = await orderApi.signMsg({
                    customerName: this.customForm.customerName, // 用户姓名
                    idNo: this.customForm.idCardNo, // 身份证号
                    bankCardNo: this.bankForm.bankCardNo, // 银行卡号
                    mobileNo: this.bankForm.mobileNo, // 手机号
                    expireDate: this.bankForm.expireDate, //信用卡有效期
                    cvv: this.bankForm.cvv, //信用卡cvv
                    tenantNo: this.tenantNo, //商户编号
                    orderNo: this.orderForm.orderNo, // 订单号
                });
                this.captchaCD = 60;
                this.captchaTimer = setInterval(() => {
                    if (this.captchaCD > 0) {
                        this.captchaCD -= 1;
                    } else {
                        clearInterval(this.captchaTimer);
                    }
                }, 1000);
                uni.showToast({ title: '验证码发送成功', icon: 'success' });
                return result;
            } catch (error) {
                uni.showToast({ title: error || '验证码发送失败', icon: 'error' });
            }
        },
        /**
         * 签约下单
         */
        async placeOrder() {
            const sumBy = require('lodash/sumBy');
            console.log('this.$data', this.$data);
            if (!this.orderForm.businessType > 0) {
                throw '请选择业务类型';
            }
            if (uni.$u.test.isEmpty(this.orderForm.totalFee)) {
                throw '请输入扣款总金额';
            }
            if (uni.$u.test.isEmpty(this.orderForm.decutionType)) {
                throw '请选择分期类型';
            }
            if (this.customForm.customerFlag != 3) {
                if (!uni.$u.test.mobile(this.bankForm.mobileNo)) {
                    throw '手机号格式错误';
                }
                if (uni.$u.test.isEmpty(this.bankForm.authCode)) {
                    throw '请输入验证码';
                }
            }
            if (this.selectedInstallMentType.dictLabel == '分期') {
                // 分期计算金额
                const total = sumBy(this.feeFormList, val => Number(val.expectDecutionFee));
                if (total != this.orderForm.totalFee) {
                    console.error('扣款金额填写错误', total, this.orderForm.totalFee)
                    throw `金额填写错误`;
                }
            } else {
                this.feeFormList = [{
                    stage: 1,
                    expectDecutionFee: this.orderForm.totalFee,
                    expectDecutionTime: uni.$u.timeFormat(new Date().getTime())
                }]
            }
            // // 签约下单
            // const result = await orderApi.placeOrder({
            //     customForm: this.customForm, // 客户信息
            //     bankForm: this.bankForm, // 银行卡信息
            //     orderForm: this.orderForm, // 订单信息
            //     feeFormList: this.feeFormList, // 账单信息
            //     tenantNo: this.tenantNo, // 商户编号
            // });
            // return result;
        },

        async submitOrder() {
            try {
                const result = await orderApi.placeOrder({
                    customForm: this.customForm, // 客户信息
                    bankForm: this.bankForm, // 银行卡信息
                    orderForm: this.orderForm, // 订单信息
                    feeFormList: this.feeFormList, // 账单信息
                    tenantNo: this.tenantNo, // 商户编号
                });
                uni.showToast({ title: '订单提交成功', icon: 'success' });
                setTimeout(() => {
                    uni.switchTab({
                        url: '/pages/index/index'
                    });
                }, 1000);
                return result;
            } catch (error) {
                const title = error?.msg || error?.message || error || '网络错误';
                uni.showToast({ title, icon: 'error' });
            }
            this.showSubmitModal = false;
        },
    }
}
</script>

<style lang="scss" scoped src="@/styles/mmv.scss"></style>